<?php

    require 'functions.php';
    
    if (!is_numeric($_POST['item_id']))
    {
        die(json_encode(array('error' => 'wrong item id')));
    }
    
    if (!is_numeric($_POST['user_id']))
    {
        die(json_encode(array('error' => 'wrong item id')));
    }
    
    if (
        !isset($_POST['positive']) || 
        (isset($_POST['positive']) && ($_POST['positive'] != 'true' && $_POST['positive'] != 'false'))
       )
    {
        die(json_encode(array('error' => 'wrong positive value')));
    }
    
    $db = DBControl::getInstance();
    
    //check if user in db
    $user = $db->PDOquery("SELECT id FROM users WHERE facebook_id = ?;", array($_POST['user_id']));
    if (!empty($user))
    {
        //if yes then obtain id
        $user_id = $user[0]['id'];
        //add item to UsersChoice
        try
        {
            if (DEBUG==false)
            {
                $db -> PDOquery('INSERT INTO userschoice (item_id, users_id, positive) VALUES (?,?,?);', array($_POST['item_id'], $user_id, $_POST['positive']));
            }
            echo json_encode(array('status' => 'success'));
        }
        catch (PDOException $e)
        {
            echo json_encode(array('error' => 'propably pair item_user,users_id already in db', 'error_message' => $e->getMessage()));
        }
    }
    else
    {
        echo json_encode(array('error' => 'non permitted attempt'));
    }
?>
